import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
//导入静态、动态、任意路由表
import { anyRoutes, dynamicRoutes, constantRoutes } from "@/router";
import _ from "lodash";
import router from "@/router/index";

//方法1：根据当前用户路由权限信息，过滤得到对应的路由对象数组 routes是动态路由数组，userRoutes是用户可以访问的路由名称列表
function filtrateAllSyncRoutes(routes, userRoutes) {
  // newRoutes存储过滤后的路由
  const newRoutes = [];
  // 循环routes
  routes.forEach((r) => {
    // 如果当前 r.name 在 userRoutes 数组中存在，则表示当前 r 可以访问，就把r添加到 newRoutes 中
    if (userRoutes.includes(r.name)) {
      if (r.children && r.children.length > 0) {
        // 当前路由有子路由
        r.children = filtrateAllSyncRoutes(r.children, userRoutes);
      }
      newRoutes.push(r);
    }
  });

  return newRoutes;
}

const getDefaultState = () => {
  return {
    token: getToken(),
    avatar: "",

    /* 用户信息 */
    buttons: [],
    name: "",
    roles: [],
    routes: [],
    // 不同角色的用户将要显示的管理菜单
    menuRoutes:constantRoutes,
  };
};

const state = getDefaultState();
/* 调用mutation用commit */
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },

  /* 设置用户信息 */
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
};
/* 调用actions用dispatch */
const actions = {
  //用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  //获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      //发送获取用户信息请求
      getInfo(state.token)
        .then((response) => {
          //解构请求的返回值
          const { data } = response;

          if (!data) {
            return reject("Verification failed, please Login again.");
          }

          const { name, avatar, buttons, roles, routes } = data;
          //触发mutation函数 改变state中的数据
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_BUTTONS", buttons);
          commit("SET_ROLES", roles);
          commit("SET_ROUTES", routes);
          // console.log("state", state);
          // console.log("data", data);

          // 1、不要直接传递dynamicRoutes
          const userRoutes = filtrateAllSyncRoutes(
            _.cloneDeep(dynamicRoutes),
            routes
          );
            // console.log('过滤后的',userRoutes);
            state.menuRoutes = [...constantRoutes, ...userRoutes];
            // console.log("menuRoutes", this.menuRoutes);
            // // 还要把路由注册到路由表中
            router.addRoutes(userRoutes);

          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
